/*
 * File Name : CatalogTreeCollection.js
 */
import Bb from 'backbone';
import CatalogTreeModel from './CatalogTreeModel.js';
import {strToFloat} from 'math.js';

const CatalogTreeCollection = Bb.Collection.extend({
    model: CatalogTreeModel,
    initialize() {
        CatalogTreeCollection.__super__.initialize.apply(this, arguments);
        this.current = this.models.filter(model => model.get('selected'));
    },
    getSelected() {
        return this.current;
    },
    allSelected() {
        return this.current.length == this.length;
    },
    setSelected(model, value) {
        let select = !model.get('selected')
        console.log('select', select)
        model.set('selected', select);
        this.current = this.models.filter(model => model.get('selected'));
        this.trigger('change:selected');

        // change une quantité nulle lorsque l'item est selectionné
        if (select && strToFloat(model.get('quantity')) == 0.) {
            this.setQuantity(model, "1")
        }
    },
    setQuantity(model, value) {
        model.set('quantity', value)
        this.trigger('change:quantity');

        const selected = (strToFloat(value) != 0.);
        
        // change la selection lorsque la quantité est nulle
        if (selected != model.get('selected')) {
            this.setSelected(model, selected)
        }
    },
    setAllSelected(models) {
        // Set all elements selected : allow to pass a list of 
        // models (in case of all selection on filtered list)
        if (models === undefined) {
            models = this.models;
        }
        this.current = models;
        this.current.forEach(item => this.setSelected(item, true))
    },
    setNoneSelected() {
        console.log("Set None selected");
        this.current.forEach(item => this.setSelected(item, false));
        this.current = [];
    }
});
export default CatalogTreeCollection;
